<template>
  <div>
    <div style="padding: 20px;">
      <div class="userInfoBox">
        <div class="avatarBox">
          <el-avatar v-if="userInfo" :src='userInfo.avatar?"/api"+userInfo.avatar:"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"' :size='100'></el-avatar>
          <el-avatar v-else :size='100'></el-avatar>
          <div style="padding: 20px 10px;width: 100px;text-align: center;">
            <span @click="avatarInfo.editAvatarFlag=true" style="color: #5191f7;">点击修改</span> <br>
            <span style="color: #999;">支持jpg,jpeg,png类型文件,2M以内</span>
          </div>
        </div>
        <div class="userInfo">
          <div style="width: 100%;margin-left: 0;font-size: 20px;">个人信息</div>
          <div>
            <p>姓名：</p><el-input v-model="userInfo.nickName" readonly></el-input>
          </div>
          <div>
            <p>性别：</p><el-input v-model="userInfo.sex" readonly></el-input>
          </div>
          <div>
            <p>教研室：</p><el-input v-model="userInfo.major" readonly></el-input>
          </div>
          <div>
            <p>工号：</p><el-input v-model="userInfo.userName" readonly></el-input>
          </div>
          <div>
            <p>电话：</p><el-input v-model="userInfo.phone" readonly></el-input>
          </div>
          <div>
            <p>邮箱：</p><el-input v-model="userInfo.email" readonly></el-input>
          </div>
          <div>
            <p>职称：</p><el-input v-model="userInfo.jobTitle[0]" readonly></el-input>
          </div>
          <div></div>
          <el-row style="margin-top: 20px;"><el-button type="primary" size="medium" @click="editUserInfo.editUserInfoFlag=true" >编辑用户信息</el-button>
          <el-button type="primary" size="medium" @click="editPasDialogFlag=true">修改密码</el-button></el-row>
        </div>
        <div>

        </div>
      </div>
      <el-dialog :visible.sync='avatarInfo.editAvatarFlag' @close='close' title='修改头像' center width="600px">
        <div class="avatarDialogBox">
          <el-upload
            class="upload-demo"
            drag
            action="/api/uploadImg"
            :on-change='preImg'
            :auto-upload='false'
            ref="upload"
            :limit="1"
            :file-list="avatarInfo.fileList"
            :multiple="false"
            :http-request='uploadAvatar'
            >
            <i class="el-icon-camera-solid" style="font-size: 67px;margin: 40px 0 16px;"></i>
            <!-- <i class="el-icon-upload"></i> -->
            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <el-button type="primary" @click="uploadAvatar">保存</el-button>
              只能上传jpg/jpeg/png文件，且不超过2M</div>
          </el-upload>
          <div class="preview">
            预览
            <div>
              <el-avatar :src="avatarInfo.previrwUrl" style="border: 50%;width: 100px;height: 100px;"></el-avatar> <br>
              100x100
            </div>
          </div>
        </div>
      </el-dialog>
      <el-dialog  :visible='editPasDialogFlag' @close='editPasDialogFlag=false' title='修改用户登录密码' center >
        <el-form :model="editPasInfo" :rules="rules" ref="form" label-width="80px">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="editPasInfo.oldPassword" show-password placeholder="请输入旧密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="editPasInfo.newPassword" show-password placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="editPasInfo.confirmPassword" show-password placeholder="请输入确认密码"></el-input>
          </el-form-item>
          <p style="text-align: center">
            <el-button type="primary" @click="editPas">提交</el-button>
            <el-button type="info" @click="resetPasInfo">重置</el-button>
          </p>
        </el-form>
      </el-dialog>
      <el-dialog @close='editUserInfo.editUserInfoFlag=false' @open='userInfoOpen' v-if="userInfo"  :visible='editUserInfo.editUserInfoFlag' title='修改用户个人信息' center >
        <el-form :model="editUserInfo" :rules="rules" ref="userInfoForm" label-width="80px">
          <el-form-item label="姓名：">
            <span>{{userInfo.nickName}}</span>
          </el-form-item>
          <el-form-item label="教研室：">
            <span>{{userInfo.major}}</span>
          </el-form-item>
          <el-form-item label="工号：">
            <span>{{userInfo.userName}}</span>
          </el-form-item>
          <el-form-item label="职称：">
            <span>{{userInfo.jobTitle[0]}}</span>
          </el-form-item>
          <el-form-item label="电话：" prop="phone">
            <el-input v-model="editUserInfo.phone" placeholder="请输入修改后的电话号码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="editUserInfo.email" placeholder="请输入修改后的邮箱地址"></el-input>
          </el-form-item>
          <p style="text-align: center">
            <el-button type="primary" @click="editUser">提交</el-button>
          </p>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import axios from "axios"
export default {
  name: "Person",
  data(){
    return{
      editPasInfo:{
        oldPassword:"",
        confirmPassword:"",
        newPassword:"",
      },
      user: this.$store.state.user,
      rules:{
        oldPassword:[{required:true,message:'请输入旧密码',trigger:"blur"}],
        confirmPassword:[{required:true,message:'请输入确认密码',trigger:"blur"}],
        newPassword:[{required:true,message:'请输入新密码',trigger:"blur"}],
        phone:[{required:true,message:'请输入电话号码',trigger:"blur"}],
        email:[{required:true,message:'请输入邮箱地址',trigger:"blur"}],
      },
      editPasDialogFlag:false,
      avatarInfo:{
        editAvatarFlag:false,
        previrwUrl:'',
        avatarFile:null,
        fileList:[]
      },
      userInfo:null,
      editUserInfo:{
        editUserInfoFlag:false,
        phone:'',
        email:'',
        userName:undefined
      }
    }
  },
  methods:{
    async initUserInfo(){
      let res= await this.$get('/api/userInfo')
      this.userInfo=res.data
      this.editUserInfo.userName= this.userInfo.userName
    },
    resetPasInfo(){
      this.editPasInfo={
        oldPassword:"",
        confirmPassword:"",
        newPassword:"",
      }
    },
    async editPas(){
      if(this.editPasInfo.confirmPassword.length<6) return this.$message.warning('密码长度必须大于六位')
      else if(this.editPasInfo.newPassword!=this.editPasInfo.confirmPassword) return this.$message.warning('新密码需与确认密码保持一致')
      let result=await this.$post('/api/change/password',this.editPasInfo)
      if(result.code==200) {
        this.editPasDialogFlag=false
        this.$message.success(result.msg)
        this.logout()
      }else this.$message.warning(result.msg)

    },
    logout() {
      this.$post("/api/logout?id=" + this.user.userId).then(res => {
        if (res.code == 200) {
          this.$router.push('/login')
          window.localStorage.clear()
          window.sessionStorage.clear()
          this.$store.commit("reset")
          Cookie.remove("token")
        }
      })
    },
    //修改头像前
    beforeAvatarUpload(file){
        const isLt2M = file.size / 1024 / 1024 < 2;
        const type=file.name.split(file.name.lastIndexOf('.'))[0]
        console.log(type)
        if (!/.*\.(png|jpeg|jpg)/.test(type)) {
          return this.$message.error('上传头像图片只能是 JPG,JPEG和PNG格式!');
        }
        if (!isLt2M) {
          return this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return 1
    },
    //修改头像
    async uploadAvatar(){
      let flag=this.beforeAvatarUpload(this.avatarInfo.avatarFile)
      if(flag!=1) return
      if(!this.avatarInfo.avatarFile)return this.$message.warning('请选择您要上传的头像')
      let formData = new FormData()
      formData.append('file',this.avatarInfo.avatarFile.raw)
      let result=await axios({
        url:'/api/uploadImg?flag=0',
        data:formData,
        method:'post',
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      result.code==200?this.$message.success('头像修改成功'):this.$message.error(result.msg)
      this.avatarInfo.editAvatarFlag=false
      this.userInfo.avatar=result.data
      this.$store.commit('updateAvatar',result.data)
    },
    preImg(file){
      this.$refs.upload.uploadFiles=[]
      if(this.avatarInfo.avatarFile){
        this.avatarInfo.avatarFile=null
      }
      this.avatarInfo.avatarFile=file
      let render =new FileReader()
      render.readAsDataURL(file.raw)
      render.onload=()=>{
        this.avatarInfo.previrwUrl=render.result
      }
    },
    close(){
      this.avatarInfo.avatarFile=null
      this.avatarInfo.previrwUrl=''
    },
    userInfoOpen(){
      this.editUserInfo.email=this.userInfo.email
      this.editUserInfo.phone=this.userInfo.phone
    },
    async editUser(){
      if(!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(this.editUserInfo.phone))return this.$message.warning('请输入正确的手机号码')
      if(!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.editUserInfo.email))return this.$message.warning('请输入正确的邮箱地址')
      let result =await this.$post('/api/edit/user',this.editUserInfo)
      result.code==200?this.$message.success('修改成功'):this.$message.error(result.msg)
      this.editUserInfo.editUserInfoFlag=false
      this.initUserInfo()
    }
  },
  mounted(){
    this.$store.commit('setTabs',{
      name: "/home/modify",
      title: "个人中心"
    })
  this.initUserInfo()
  },
}
</script>

<style scoped lang="scss">
.userInfoBox{
  display: flex;
  .avatarBox{
    font-size: 12px;
    text-align: center;
    // display: flex;
    // align-items: flex-end;
  }
  .userInfo{
    margin-top: 5px;
    margin-left: 30px;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    font-size: 12px;
    >div{
     width: 45%;
     margin-left: 20px;
    color: #999;

    }
    p{
      margin: 10px 0;
    }
  }
}
.avatarDialogBox{
  display: flex;
  .preview{
    display: flex;
    flex-direction: column;
    color:#999;
    width: 200px;
    align-items: center;
    text-align: center;
    >div{
      margin: 15px 0;
    }
  }
}
 .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
    &:first-child{
      color: #999;
    }
  }
  /deep/ .el-input__inner:focus{
    border-color: #DCDFE6;
    outline: 0;
  }
</style>
